import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入登录组件
import Login from '@/views/login/index'
// 引入layout组件
// import Layout from '@/views/layout/Layout'
// 引入文章二级路由组件
// import Fans from '@/views/Fans'
// import Image from '@/views/Image'
// import Setting from '@/views/Setting'
// import Home from '@/views/Home'
import NotFound from '@/views/NotFound'
// 引入本地存储
import {getToken} from '@/store'
import Test from '@/test/formtest'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path:'/',
    name:'Layout',
    component:()=>import(/* webpackChunkName: "layout" */ '@/views/layout/Layout'),
    redirect:'/home',
    children:[
      {path:'articles',
      component:() => import(/* webpackChunkName: "articles" */ '@/views/Article'),
      name:'articles'},
      {path:'addArticle',
      component:()=>import(/*webpackChunkName:"addarticle" */ '@/views/AddArticle'),
      name:'addArticle'},
      {path:'comment',
      component:()=>import(/*webpackChunkName:"comment" */ '@/views/Comment'),
      name:'comment'},
      {path:'editArticle',
      component:()=>import(/*webpackChunkName:"editarticle" */ '@/views/EditArticle'),
      name:'editArticle'},
      {path:'fans',
      component:()=>import(/*webpackChunkName:"fans" */ '@/views/Fans'),
      name:'fans'},
      {path:'image',
      component:()=>import(/*webpackChunkName:"image" */ '@/views/Image'),
      name:'image'},
      {path:'setting',
      component:()=>import(/*webpackChunkName:"setting" */ '@/views/Setting'),
      name:'setting'},
      {path:'home',
      component:()=>import(/*webpackChunkName:"home" */ '@/views/Home'),
      name:'home'},

    ]
  },
  // 测试路由
  {path:'/test',component:Test,name:'Test'},
  {path:'*',component:NotFound}
]

const router = new VueRouter({
  routes
})

// 导航守卫：每次路由跳转都会触发导航守卫，利用导航守卫控制页面跳转的权限
// 除了登录和注册页面，别的页面都需要验证token
router.beforeEach((to,from,next)=>{
  // console.log(to,from,next);
  // next();
  if(to.path === '/login' || to.path === '/register'){
    next();
  }else {
    let usertoken = getToken();
    if(usertoken && usertoken.token){
      next(); 
    }else {
      next('/login');
    }
  }
})





export default router
